package org.ccheng.xztx.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.reactivex.Observable;
import org.ccheng.xztx.domain.SportUser;
import org.ccheng.xztx.domain.TianWuInfo;
import org.ccheng.xztx.domain.TianWuUser;
import org.ccheng.xztx.domain.UserInfo;
import org.ccheng.xztx.service.TianWuService;
import org.ccheng.xztx.service.UserService;
import org.ccheng.xztx.util.Api;
import org.ccheng.xztx.util.ApiConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class TianWuServiceImpl implements TianWuService {

    private static final String I = "[天武]：";

    @Autowired
    private UserService userService;

    public JSONObject findRival() {
        String response = Api.get(ApiConstants.API_TIAN_WU_INDEX);

        JSONObject obj = JSONUtil.createObj();
        obj.putOpt("num", ReUtil.get("(?<=今日剩余次数:)\\d+", response, 0));// 获取剩余挑战次数

        List<String> ids = ReUtil.findAll("(?<=otherId=)\\d+(?='>挑战)", response, 0);
        obj.putOpt("ids", ids);

        return obj;
    }

    public void PK(Long myAtk) {

        JSONObject obj = findRival();

        UserInfo lastEnemy = null;

        // 获取所有对手
        List<String> ids = obj.get("ids", List.class);
        for (String id : ids) {
            UserInfo enemy = userService.findById(id);

            Long enemyAtk = Long.parseLong(enemy.getAttack());

            if (myAtk > enemyAtk) {
                lastEnemy = enemy;
                break;
            }
        }

        if (lastEnemy == null) {
            Api.out(I, "当前没有能够战胜的目标，等待5分钟后重试");
            return;
        }

        Api.out(I, "尝试进攻目标[", lastEnemy.getUsername(), "]   ID:", lastEnemy.getId());

        Map<String, Object> params = MapUtil.newHashMap();
        params.put("otherId", lastEnemy.getId());
        String response = Api.get(ApiConstants.API_TIAN_WU_PK, params);

        String result = ReUtil.get("(?<=天武榜<br/>).{0,80}(?=<a)|(?<=<div class=\"gaps normal\">).{0,20}(?=<br/><)", response, 0);
        Api.out(I, "挑战结果：" + result);
    }

    public void auto() {
        Api.out(I, "开始自动挑战");

        JSONObject obj = findRival();
        int num = obj.getInt("num");

        if (num < 1) {
            Api.out(I, "挑战次数不足");
        }

        UserInfo userInfo = userService.findById(null);
        Long myAtk = Long.parseLong(userInfo.getAttack());

        for (int i = 0; i < num; i++) {
            PK(myAtk);
        }

        Api.out(I, "挑战结束");
        Api.out(I, "共执行：" + num + "次");
    }

    public static void main(String[] args) {
        new TianWuServiceImpl().auto();
    }
}
